<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <header class="dashboard-header">
      <div class="container">
        <div class="header-content">
          <div class="brand">
            <div class="brand-icon">
              <i class="fas fa-chart-line text-xl"></i>
            </div>
            <div class="brand-text">
              <h1>SEO监控面板</h1>
              <p>外链质量与网站健康度监控</p>
            </div>
          </div>
          <div class="header-actions">
            <router-link to="/online_semrush" class="refresh-btn">
              <i class="fas fa-paper-plane mr-2"></i>在线提交
            </router-link>
            <button class="refresh-btn" @click="refreshData">
              <i class="fas fa-sync-alt mr-2"></i>刷新
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="dashboard-main">
      <!-- Stats Cards -->
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-card-header">
            <div class="stat-card-icon bg-blue-100">
              <i class="fas fa-link text-blue-600"></i>
            </div>
                          <div class="stat-card-value">
                <div class="number">{{ siteInfo?.backlink_count || 0 }}</div>
                <div class="label">总外链数</div>
              </div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: '75%' }"></div>
          </div>
          <!-- <div class="stat-card-trend">
            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
            相比上周 +12%
          </div> -->
        </div>

        <div class="stat-card">
          <div class="stat-card-header">
            <div class="stat-card-icon bg-green-100">
              <i class="fas fa-check-circle text-green-600"></i>
            </div>
            <div class="stat-card-value">
              <div class="number">{{ siteInfo?.site_count || 0 }}</div>
              <div class="label">站点数</div>
            </div>
          </div>
        </div>

        <!-- <div class="stat-card">
          <div class="stat-card-header">
            <div class="stat-card-icon bg-yellow-100">
              <i class="fab fa-google text-yellow-600"></i>
            </div>
            <div class="stat-card-value">
              <div class="number">{{ googleFriendly }}</div>
              <div class="label">Google友好</div>
            </div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: '68%' }"></div>
          </div>
          <div class="stat-card-trend">
            <i class="fas fa-arrow-down text-red-500 mr-1"></i>
            友好度 {{ googleFriendlyRate }}%
          </div>
        </div> -->

        <!-- <div class="stat-card">
          <div class="stat-card-header">
            <div class="stat-card-icon bg-purple-100">
              <i class="fas fa-globe text-purple-600"></i>
            </div>
                          <div class="stat-card-value">
                <div class="number">{{ siteInfo?.site_count || 0 }}</div>
                <div class="label">监控站点</div>
              </div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: '92%' }"></div>
          </div>
          <div class="stat-card-trend">
            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
            本月新增 +{{ sites.length > 10 ? 8 : sites.length }}
          </div>
        </div> -->
      </div>

      <!-- Filter & Controls -->
      <div class="filter-section">
        <div class="filter-content">
          <div class="filter-left">
            <div class="search-container">
              <select class="search-type-select" v-model="searchType" @change="handleSearchTypeChange">
                <option value="taskid">Task ID</option>
                <option value="site_url">站点URL</option>
              </select>
              <div class="search-input">
                <i class="fas fa-search search-icon"></i>
                <input 
                  type="text" 
                  :placeholder="getSearchPlaceholder()"
                  v-model="searchQuery"
                  @keyup.enter="handleSearch"
                  @input="handleSearchInput"
                />
                <button 
                  type="button" 
                  class="search-btn" 
                  @click="handleSearch"
                  :disabled="loading"
                >
                  <i class="fas fa-search"></i>
                </button>
              </div>
            </div>
                          <select class="filter-select" v-model="statusFilter" @change="handleStatusFilter">
                <option value="">全部状态</option>
                <option value="has_word">出词外链</option>
                <option value="backlink_traffic">有流量外链</option>
                <option value="has_word,backlink_traffic">出词,有流量外链</option>
              </select>
            <!-- <select class="filter-select" v-model="googleFilter" @change="handleGoogleFilter">
              <option value="">Google友好度</option>
              <option value="friendly">友好</option>
              <option value="unfriendly">不友好</option>
              <option value="unknown">未知</option>
            </select> -->
          </div>
          <div class="filter-right">
            <button class="btn-primary" @click="exportAllData">
              <i class="fas fa-download mr-2"></i>导出全量数据
            </button>
            <button class="btn-secondary" @click="exportExcel" :disabled="loading">
              <i class="fas fa-download mr-2"></i>
              <span v-if="exporting">导出中...</span>
              <span v-else>导出数据</span>
            </button>
          </div>
        </div>
      </div>

      <!-- Data Table -->
      <div class="data-table">
        <div class="table-header">
          <div class="table-header-content">
            <h2 class="table-title">外链监控数据</h2>
            <div class="table-controls">
              <span>显示</span>
              <select v-model="pageSize" @change="handlePageSizeChange">
                <option :value="10">10</option>
                <option :value="25">25</option>
                <option :value="50">50</option>
              </select>
              <span>条记录</span>
            </div>
          </div>
        </div>

        <div class="table-wrapper">
          <table class="modern-table">
            <thead>
              <tr>
                <th>
                  <div class="sort-header">
                    <span>Task ID</span>
                    <i class="fas fa-sort text-gray-400"></i>
                  </div>
                </th>
                <th>
                  <div class="sort-header">
                    <span>站点信息</span>
                    <i class="fas fa-sort text-gray-400"></i>
                  </div>
                </th>
                <th>站点收录数</th>
                <th>锚文本</th>
                <th>外链地址</th>
                <th>客户链接</th>
                <th>外链状态 (site:精确外链结果)</th>
                <th>外链Google友好度</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(site, index) in sites" :key="site.id" class="fade-in">
                <td>
                  <div class="task-id-cell">
                    <div class="task-id-icon">
                      <i class="fas fa-hashtag text-blue-600 text-xs"></i>
                    </div>
                    <span class="task-id-text">{{ site.backlinks[0]?.taskid || '-' }}</span>
                  </div>
                </td>
                <td>
                  <div class="site-info-cell">
                    <div class="site-avatar" :class="getSiteAvatarClass(index)">
                      <i :class="getSiteIcon(site.domain)"></i>
                    </div>
                    <div class="site-details">
                      <div class="site-name">{{ formatDomain(site.domain) }}</div>
                      <!-- <div class="site-type">{{ getSiteType(site.domain) }}</div> -->
                    </div>
                  </div>
                </td>
                <td class="result-count-cell">
                  <span class="result-count-number">
                    {{ formatResultCount(site.google_search?.resultCount || 0) }}
                  </span>
                </td>
                <td>
                  <span class="anchor-tag" :class="getAnchorTagClass(index)">
                    {{ site.backlinks[0]?.anchor_text || '-' }}
                  </span>
                </td>
                <td>
                  <div class="tooltip">
                    <a 
                      :href="site.backlinks[0]?.original_url" 
                      target="_blank"
                      class="url-link"
                      @click="handleUrlClick(site.backlinks[0]?.original_url)"
                    >
                      {{ truncateUrl(site.backlinks[0]?.original_url) }}
                    </a>
                    <span class="tooltiptext">点击查看完整链接</span>
                  </div>
                </td>
                <td>
                  <div class="tooltip">
                    <a 
                      :href="site.backlinks[0]?.resolved_url" 
                      target="_blank"
                      class="url-link text-green-600 hover:text-green-800"
                      @click="handleUrlClick(site.backlinks[0]?.resolved_url)"
                    >
                      {{ truncateUrl(site.backlinks[0]?.resolved_url) }}
                    </a>
                    <span class="tooltiptext">点击查看完整链接</span>
                  </div>
                </td>
                <td>
                  <span class="status-tag" :class="getStatusTagClass(site.backlinks[0]?.domain_match?.google_sites)">
                    <span class="status-dot" :class="getStatusDotClass(site.backlinks[0]?.domain_match?.google_sites)"></span>
                    {{ site.backlinks[0]?.domain_match?.google_sites ? '收录' : '未收录' }}
                  </span>
                </td>
                <td>
                  <el-popover
                    placement="right"
                    :width="400"
                    trigger="hover"
                    popper-class="rounded-lg shadow-lg"
                  >
                    <template #default>
                      <div class="p-4">
                        <div class="space-y-3">
                          <div class="flex justify-between">
                            <span class="text-gray-600 font-medium">检查时间：</span>
                            <span class="text-gray-900">{{ formatTime(site.backlinks[0]?.google_indexed?.check_time) }}</span>
                          </div>
                          <div class="flex justify-between">
                            <span class="text-gray-600 font-medium">状态码：</span>
                            <span class="text-gray-900">{{ site.backlinks[0]?.google_indexed?.status_code || '-' }}</span>
                          </div>
                          <div class="flex justify-between">
                            <span class="text-gray-600 font-medium">消息：</span>
                            <span class="text-gray-900">{{ site.backlinks[0]?.google_indexed?.message || '-' }}</span>
                          </div>
                          <div v-if="site.backlinks[0]?.google_indexed?.details" class="border-t pt-3">
                            <span class="text-gray-600 font-medium">详细信息：</span>
                            <pre class="text-xs text-gray-700 mt-2 p-2 bg-gray-50 rounded overflow-auto">{{ JSON.stringify(site.backlinks[0]?.google_indexed?.details, null, 2) }}</pre>
                          </div>
                        </div>
                      </div>
                    </template>
                    <template #reference>
                      <div class="tooltip">
                        <span class="status-tag cursor-help" :class="getGoogleStatusTagClass(site.backlinks[0]?.google_indexed?.is_indexed)">
                          <span class="status-dot" :class="getGoogleStatusDotClass(site.backlinks[0]?.google_indexed?.is_indexed)"></span>
                          {{ site.backlinks[0]?.google_indexed?.is_indexed ? '友好' : '不友好' }}
                        </span>
                        <span class="tooltiptext">检查时间: {{ formatTime(site.backlinks[0]?.google_indexed?.check_time) }}<br>状态码: {{ site.backlinks[0]?.google_indexed?.status_code || '-' }}</span>
                      </div>
                    </template>
                  </el-popover>
                </td>
                <td>
                  <button 
                    class="action-btn"
                    @click="loadTrends(site.backlinks[0]?.id || 0, site.backlinks[0]?.taskid || '-', site.domain)"
                    :disabled="loading"
                  >
                    <i class="fas fa-chart-bar mr-2"></i>
                    <span v-if="loading">加载中...</span>
                    <span v-else>SEMRUSH数据</span>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div class="pagination">
          <div class="pagination-content">
            <div class="pagination-info">
              <span>显示</span>
              <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, total) }}</span>
              <span>共</span>
              <span class="font-medium">{{ total }}</span>
              <span>条记录</span>
            </div>
            <div class="pagination-controls">
              <button 
                class="pagination-btn"
                :disabled="currentPage <= 1"
                @click="handlePrevPage"
              >
                <i class="fas fa-chevron-left mr-2"></i>
                上一页
              </button>
              <div class="pagination-numbers">
                <button 
                  v-for="page in getPageNumbers()" 
                  :key="page"
                  class="pagination-number"
                  :class="{ active: page === currentPage }"
                  @click="goToPage(page)"
                  v-if="page !== '...'"
                >
                  {{ page }}
                </button>
                <span v-else class="pagination-ellipsis">...</span>
              </div>
              <button 
                class="pagination-btn"
                @click="handleNextPage"
              >
                下一页
                <i class="fas fa-chevron-right ml-2"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- TrendDialog -->
    <TrendDialog
      v-model:visible="dialogVisible"
      :data="currentSiteData"
      :site-id="currentSiteId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import TrendDialog from './TrendDialog.vue';
import { BASE_URL } from '../main';

// 接口定义
interface Backlink {
  id: number;
  anchor_text: string;
  original_url: string;
  resolved_url: string;
  domain_match: string;
  google_indexed: {
    is_indexed: boolean;
    check_time: string;
    message: string;
    status_code: number;
    details: any;
  } | null;
  taskid: string;
}

interface SemrushData {
  id?: number;
  taskId?: string;
  domain?: string;
  traffic_data?: {
    organic: number;
    paid: number;
  };
  traffic_trend?: {
    dates: string[];
    organic: number[];
    paid: number[];
  };
  keyword_search_trend?: {
    dates: string[];
    count: number[];
    avg_position: number[];
  };
  top_keywords?: {
    keyword: string;
    position: number;
    traffic: number;
    change: number;
  }[];
  overview_trend?: {
    data: {
      traffic: number;
      trafficBranded: number;
      trafficNonBranded: number;
      trafficCost: number;
      date: string;
      organicPositionsTrend: number[];
      serpFeaturesPositions: number;
    }[];
  };
}

interface Site {
  domain: string;
  site_url: string;
  id: number;
  user_id: number;
  backlinks: Backlink[];
  semrush_data: SemrushData;
}

// 响应式数据
const sites = ref<Site[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const exporting = ref(false);
const dialogVisible = ref(false);
const currentSiteData = ref<any>(null);
const currentSiteId = ref<number>(0);
const searchQuery = ref('');
const searchType = ref('taskid'); // 默认搜索类型为taskid
const statusFilter = ref('');
const googleFilter = ref('');

// 计算属性
const totalLinks = computed(() => {
  return sites.value.reduce((sum, site) => sum + site.backlinks.length, 0);
});

const validLinks = computed(() => {
  return sites.value.reduce((sum, site) => {
    return sum + site.backlinks.filter(link => link.domain_match !== 'error').length;
  }, 0);
});

const validLinkRate = computed(() => {
  return totalLinks.value > 0 ? ((validLinks.value / totalLinks.value) * 100).toFixed(1) : '0.0';
});

const googleFriendly = computed(() => {
  return sites.value.reduce((sum, site) => {
    return sum + site.backlinks.filter(link => link.google_indexed?.is_indexed).length;
  }, 0);
});

const googleFriendlyRate = computed(() => {
  return totalLinks.value > 0 ? ((googleFriendly.value / totalLinks.value) * 100).toFixed(1) : '0.0';
});

// 工具函数
const formatCurrentTime = () => {
  return new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

const formatTime = (timeStr: string | undefined) => {
  if (!timeStr) return '-';
  try {
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    });
  } catch (e) {
    return timeStr;
  }
};

const formatDomain = (url: string): string => {
  try {
    const domain = url.replace(/^https?:\/\//i, '').replace(/^www\./i, '').split('/')[0];
    return domain;
  } catch (e) {
    return url;
  }
};

const formatResultCount = (count: number): string => {
  if (count === 0) return '0';
  
  if (count >= 1000000000) {
    return `${(count / 1000000000).toFixed(1)}B`;
  } else if (count >= 1000000) {
    return `${(count / 1000000).toFixed(1)}M`;
  } else if (count >= 1000) {
    return `${(count / 1000).toFixed(1)}K`;
  }
  
  return count.toString();
};

const truncateUrl = (url: string | undefined): string => {
  if (!url) return '-';
  return url.length > 40 ? url.substring(0, 40) + '...' : url;
};

const getSiteAvatarClass = (index: number): string => {
  const colors = [
    'bg-gradient-to-r from-blue-500 to-purple-600',
    'bg-gradient-to-r from-green-500 to-blue-600',
    'bg-gradient-to-r from-orange-500 to-red-600',
    'bg-gradient-to-r from-purple-500 to-pink-600',
    'bg-gradient-to-r from-indigo-500 to-blue-600'
  ];
  return colors[index % colors.length];
};

const getSiteIcon = (domain: string): string => {
  if (domain.includes('news') || domain.includes('journal')) return 'fas fa-newspaper';
  if (domain.includes('business')) return 'fas fa-briefcase';
  if (domain.includes('media') || domain.includes('digital')) return 'fas fa-digital-tachograph';
  if (domain.includes('tech') || domain.includes('software')) return 'fas fa-code';
  return 'fas fa-globe';
};

const getSiteType = (domain: string): string => {
  if (domain.includes('news') || domain.includes('journal')) return '新闻资讯';
  if (domain.includes('business')) return '商业咨询';
  if (domain.includes('media') || domain.includes('digital')) return '数字媒体';
  if (domain.includes('tech') || domain.includes('software')) return '技术服务';
  return '综合站点';
};

const getAnchorTagClass = (index: number): string => {
  const classes = ['blue', 'purple', 'green'];
  return classes[index % classes.length];
};

const getStatusTagClass = (status: boolean): string => {
  return status ? 'success' : 'error';
};

const getStatusDotClass = (status: boolean): string => {
  return status ? 'bg-green-500' : 'bg-red-500';
};

const getGoogleStatusTagClass = (isIndexed: boolean): string => {
  return isIndexed ? 'success' : 'warning';
};

const getGoogleStatusDotClass = (isIndexed: boolean): string => {
  return isIndexed ? 'bg-green-500' : 'bg-yellow-500';
};

const getPageNumbers = () => {
  const totalPages = Math.ceil(total.value / pageSize.value);
  const pages = [];
  const maxVisible = 5;
  
  if (totalPages <= maxVisible) {
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (currentPage.value <= 3) {
      for (let i = 1; i <= 4; i++) {
        pages.push(i);
      }
      pages.push('...');
      pages.push(totalPages);
    } else if (currentPage.value >= totalPages - 2) {
      pages.push(1);
      pages.push('...');
      for (let i = totalPages - 3; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      pages.push(1);
      pages.push('...');
      pages.push(currentPage.value - 1);
      pages.push(currentPage.value);
      pages.push(currentPage.value + 1);
      pages.push('...');
      pages.push(totalPages);
    }
  }
  
  return pages;
};

// 事件处理函数
const handleUrlClick = (url: string) => {
  if (url) {
    window.open(url, '_blank');
  }
};

const refreshData = async () => {
  await fetchSites();
  ElMessage.success('数据已刷新');
};

// 获取搜索占位符文本
const getSearchPlaceholder = () => {
  switch (searchType.value) {
    case 'taskid':
      return '请输入Task ID，如：510934';
    case 'site_url':
      return '请输入站点URL，如：journalnewsinfo.com';
    default:
      return '请输入搜索内容...';
  }
};

// 处理搜索类型变化
const handleSearchTypeChange = () => {
  // 清空搜索框
  searchQuery.value = '';
  // 重置到第一页并重新加载数据
  currentPage.value = 1;
  fetchSites();
};

// 搜索输入变化时的处理（可以用于实时搜索或其他逻辑）
const handleSearchInput = () => {
  // 如果搜索框被清空，自动重新加载数据
  if (!searchQuery.value || searchQuery.value.trim() === '') {
    currentPage.value = 1;
    fetchSites();
  }
  // 可以在这里添加防抖逻辑或其他实时搜索逻辑
};

// 执行搜索（回车键触发）
const handleSearch = () => {
  console.log('搜索:', searchQuery.value);
  // 重置到第一页并重新请求数据
  currentPage.value = 1;
  fetchSites();
};

const handleStatusFilter = () => {
  // 重置到第一页并重新请求数据
  currentPage.value = 1;
  fetchSites();
};

const handleGoogleFilter = () => {
  // 实现Google友好度过滤逻辑
  console.log('Google过滤:', googleFilter.value);
};

const handlePageSizeChange = () => {
  currentPage.value = 1;
  fetchSites();
};

const loadTrends = async (siteId: number, taskId: string, domain: string) => {
  try {
    loading.value = true;
    const response = await axios.get(`${BASE_URL}/api/v1/sites/${siteId}/detail-data`);
    currentSiteData.value = {
      ...response.data,
      taskId,
      domain
    };
    currentSiteId.value = siteId;
    dialogVisible.value = true;
  } catch (error) {
    console.error('Error loading trends:', error);
    ElMessage.error('加载趋势数据失败');
  } finally {
    loading.value = false;
  }
};

const exportExcel = async () => {
  try {
    exporting.value = true;
    
    // 获取当前页面所有backlink的ID
    const backlinkIds: number[] = [];
    sites.value.forEach(site => {
      site.backlinks.forEach(backlink => {
        if (backlink.id) {
          backlinkIds.push(backlink.id);
        }
      });
    });

    if (backlinkIds.length === 0) {
      ElMessage.warning('当前页面没有可导出的数据');
      return;
    }

    // 准备请求体
    const requestBody = {
      ids: backlinkIds,
      all: 0,
      columns: [
        "taskid", 
        "site",
        "anchor_text",
        "backlink_url",
        "client_url",
        "backlink_status",
        "backlink_google_friendly",
        // "has_word",
        "backlink_traffic",
        "word_count",
        "completed_time"
      ]
    };

    // 发送导出请求
    const response = await axios.post(`${BASE_URL}/api/v1/backlinks/export/excel`, requestBody, {
      responseType: 'blob', // 重要：设置响应类型为blob以处理文件下载
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 设置文件名
    const currentTime = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
    link.download = `外链数据导出_${currentTime}.xlsx`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success(`成功导出 ${backlinkIds.length} 条数据`);

  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出数据失败，请稍后重试');
  } finally {
    exporting.value = false;
  }
};

const exportAllData = async () => {
  try {
    exporting.value = true;
    
    // 准备全量导出请求体
    const requestBody = {
      ids: [], // 全量导出时ids可以为空
      all: 1,  // 关键：设置为1表示导出全量数据
      columns: [
        "taskid", 
        "site",
        "anchor_text",
        "backlink_url",
        "client_url",
        "backlink_status",
        "backlink_google_friendly",
        // "has_word",
        "backlink_traffic",
        "word_count",
        "completed_time"
      ]
    };

    // 发送导出请求
    const response = await axios.post(`${BASE_URL}/api/v1/backlinks/export/excel`, requestBody, {
      responseType: 'blob', // 重要：设置响应类型为blob以处理文件下载
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 设置文件名
    const currentTime = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
    link.download = `外链全量数据导出_${currentTime}.xlsx`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('成功导出全量数据');

  } catch (error) {
    console.error('全量导出失败:', error);
    ElMessage.error('全量导出数据失败，请稍后重试');
  } finally {
    exporting.value = false;
  }
};

const fetchSites = async () => {
  try {
    loading.value = true;
    // 构造基础URL
    let url = `${BASE_URL}/api/v1/sites/with-detail?skip=${(currentPage.value - 1) * pageSize.value}&limit=${pageSize.value}`;
    
    // 构造filters数组
    const filters = [];
    
    // 添加状态过滤条件
    if (statusFilter.value && statusFilter.value.trim() !== '') {
      filters.push(statusFilter.value);
    }
    
    // 添加搜索查询条件
    if (searchQuery.value && searchQuery.value.trim() !== '') {
      // 根据搜索类型添加不同的filter
      if (searchType.value === 'taskid') {
        filters.push('taskid');
      } else if (searchType.value === 'site_url') {
        filters.push('site_url');
      }
    }
    
    // 将filters添加到URL
    if (filters.length > 0) {
      url += `&filters=${filters.join(',')}`;
    }
    
    // 添加搜索查询参数
    if (searchQuery.value && searchQuery.value.trim() !== '') {
      url += `&query_text=${encodeURIComponent(searchQuery.value.trim())}`;
    }
    
    console.log('请求URL:', url);
    console.log('当前过滤条件:', statusFilter.value);
    console.log('搜索类型:', searchType.value);
    console.log('搜索查询:', searchQuery.value);
    
    const response = await axios.get(url);
    sites.value = response.data.items;
    total.value = response.data.total || response.data.items.length;
  } catch (error) {
    console.error('Error fetching sites:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

const siteInfo = ref<any>(null);
const getSiteInfo = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/api/v1/sites/dashboard/info`);
    siteInfo.value = response.data;
  } catch (error) {
    console.error('Error fetching site info:', error);
    ElMessage.error('获取站点信息失败');
  }
};

const handlePrevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchSites();
  }
};

const handleNextPage = () => {
  currentPage.value++;
  fetchSites();
};

const goToPage = (page: number) => {
  if (typeof(page) !== 'number') return;
  currentPage.value = page;
  fetchSites();
};

// 生命周期
onMounted(() => {
  getSiteInfo();
  fetchSites();
});
</script>

<style scoped>
/* 组件特定样式 */
.fade-in {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 结果数量列样式 */
.result-count-cell {
  width: 60px;
  max-width: 60px;
  min-width: 50px;
  text-align: center;
  padding: 6px 2px;
}

.result-count-number {
  display: inline-block;
  font-weight: 600;
  font-size: 0.75rem;
  color: #374151;
  background: #f3f4f6;
  padding: 3px 6px;
  border-radius: 4px;
  white-space: nowrap;
  text-align: center;
  min-width: 30px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .result-count-cell {
    width: 50px;
    max-width: 50px;
    min-width: 45px;
  }
  
  .result-count-number {
    font-size: 0.7rem;
    padding: 2px 4px;
    min-width: 25px;
  }
  
  .filter-left {
    flex-direction: column;
    space-y: 1rem;
  }
  
  .table-wrapper {
    font-size: 0.875rem;
  }
  
  .modern-table td {
    padding: 0.75rem 0.5rem;
  }
}
</style> 
